<?
	ob_start();
	header('Content-Type:application/json; charset=utf8');
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
	header("Cache-Control: no-cache, must-revalidate");
	header("Pramga: no-cache");
	header('Access-Control-Allow-Origin: *');
	// 链接数据库
	include_once('include/conn_db.php');
	include_once('include/db_class.php');
	mysql_connect(HOST,NAME,PASS) or die(mysql_error());
	mysql_select_db(DBNAME);
	mysql_query('SET NAMES '.CODEPAGE);
	$mydb = new mydb();
	/**************************************
	********这个文件应该是用于wx.login()********
	***************************************/
	// 初始化
	$unionid = '';
	$openid= '';


	///////////////////////////////////和微信沟通//////////////////////////////////////
	/**/
	$js_code = $_POST['jscode'];
	$appid = "wxf8882d2559d49ba8";
	$secret = "b081889e22ef5cc2f9855173264eb87d";
	$grant_type = "authorization_code";

	#开始使用curl
	$curl = curl_init();

	#使用curl_setopt() 设置要获得url地址
	 $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=' . $grant_type;
	 curl_setopt($curl, CURLOPT_URL, $url);

	#设置是否输出header
	 curl_setopt($curl, CURLOPT_HEADER, false);

	#设置是否输出结果
	 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	#设置是否检查服务器端的证书
	 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

	#使用curl_exec()将curl返回的结果转换成正常数据并保存到一个变量中
	 $data = curl_exec($curl);
	 $wx_json_obj = json_decode($data,true);
	#关闭会话
	 curl_close($curl);

	# 赋予变量
	$openid = $wx_json_obj['openid'];
	$unionid = $wx_json_obj['unionid']; // 先不取得unionid

	
	////////////////////////////////////得到openid和unionid后，新建用户//////////////////////////////
	$cmd_find = "select * from {$TABLE_C}user where openid = '$openid' or unionid = '$unionid'";
	// echo $mydb->num_rows($cmd_find);
	if($mydb->num_rows($cmd_find)==0){
		#不存在,则新建用户
		$mydb->query("insert into {$TABLE_C}user (openid,unionid,datetime) values ('$openid','$unionid',NOW())");
	}else{
		#存在用户，如果有得到unionid,就更新
		$unionid && $mydb->query("update {$TABLE_C}user set unionid='$unionid' where openid = '$openid'");
	}

	// ////////////////////////////////////////////返回给前端//////////////////////////////////////
	$results = array(
		'code'=>0,
		'openid' => $openid,
		'unionid' => $unionid,
		'session_key' => $wx_json_obj['session_key'],
		'msg'=>'返回了数据！'
	);
	echo json_encode($results);

	// 结束
	mysql_close();
?>